package io.github.enbool.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;

public class KeyUtil {
	
	private static final String PODUCT = "2";
	private static final String ACTIVITY = "3";
	private static final String GIFT = "5";
	
	private static final String WITHDRAW = "8";
	private static final String REFUND = "9";
	
	public static String getProductOrderNo(Long userId) {
		return PODUCT + generateOrderNo(userId);
	}
	
	public static String getActivityOrderNo(Long userId) {
		return ACTIVITY + generateOrderNo(userId);
	}
	
	public static String getGiftOrderNo(Long userId) {
		return GIFT + generateOrderNo(userId);
	}
	
	public static String getWithDrawOrderNo(Long userId) {
		return WITHDRAW + generateOrderNo(userId);
	}
	
	public static String getRefundOrderNo(Long userId) {
		return REFUND + generateOrderNo(userId);
	}

	private static String generateOrderNo(Long userId) {
		
		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
		String timeStr = df.format(LocalDateTime.now());
		
		long id = 100000 + userId % 100000;
		String randStr = RandomStringUtils.randomNumeric(4);
		
		return timeStr + id + randStr + sign(id, randStr);
	}	
	
	private static long sign(long id, String randStr) {
		long tmp = id % 31 + Long.valueOf(randStr) % 53 + 10;
		return tmp;
	}
	
	public static Long[] generateRandomSet(final long startInclusive, final long endExclusive, final int size){
		Set<Long> tmp = new HashSet<>();
		while(tmp.size() < size) {
			tmp.add(RandomUtils.nextLong(startInclusive, endExclusive));
		}
		Long[] ret = new Long[tmp.size()];
		tmp.toArray(ret);
		
		return ret;
	}
}
